<!doctype html>
<html>
<head>
	<meta charset="utf-8">
	<link rel="stylesheet" type="text/css" href="./style.css" />
	<script src="./jquery-1.8.3.js"></script>
	<script src="./date.format.js"></script>
	<script>
	{
		var _user = "";
		var _userkey = "";
		
		var _users = [];
		
		window.onbeforeunload = function() {
			var date = (new Date());				
			var timestamp = Math.round((date.getTime() + (date.getTimezoneOffset() * 60000)) / 1000);
			
			var msg = { entity : "user", action : "logout", user : _user, userkey: _userkey, datetime : timestamp, };
			
			console.log(msg);
			
			$.ajax( {
				url: "./transceiver.php",
				type: "POST",
				data: msg,
				async: false
			} );
			
			sleep(3000);
			setTimeout(function(){}, 3000);
		}
		
		$(document).ready( function () {
			$("#chat ul").empty();
			$("#privatePanel").hide();
			{
				var date = (new Date());
				var timestamp = date.getTime() + (date.getTimezoneOffset() * 60000);
				var msg = { entity : "user", action : "login", datetime : timestamp, };
				console.log (msg);
				$.ajax( {
					url: "./transceiver.php",
					type: "POST",
					data: msg
				} ).done( function (data) {
					
					data = $.parseJSON(data);
					console.log (data);
					if (data.success) {
						
						_user = data.username;
						_userkey = data.userkey;
						
						window.setInterval(function(){
							var timestamp = date.getTime() + (date.getTimezoneOffset() * 60000);
							var msg = { entity : "user", action : "get_list", datetime : timestamp, };
							$.ajax({ 
								url: "./transceiver.php",
								type: "POST",
								data: msg,
								success: function(data){
									data = $.parseJSON(data);
									
									console.log (data);
									if (data.success) {
										$("#contacts ul").empty();
										
										if (data.users) {
											_users = data.users;
											
											for (key in data.users) {
												if (key != 0) {
													user = data.users[key].username;
													//console.log(data.users[key], user);
													
													user = $('<span></span>').append(user + "");
													$("#contacts ul").append( $('<li></li>').append( user ) );
													
													$(user).click( function() {
														$("#privatePanel").show();
														$("#private-name").text($(this).text());
														for (key in _users) {
															if (key != 0) {
																console.log(_users[key], $(this).text());
																if (_users[key].username == $(this).text()) {
																	$("#private-key").attr( "value", _users[key].userkey );
																	//console.log($("#private-key").attr("value"), _users[key].userkey);
																}
															}
														}
													});													
												}
											}
										}
									}
								}
							});
						}, 1000);
						
						
						window.setInterval(function(){
							var date = (new Date());
							var timestamp = Math.round((date.getTime() + (date.getTimezoneOffset() * 60000)) / 1000);
							
							var msg = { entity : "post", action : "get_list", user : _user, userkey : _userkey, datetime : timestamp, };
							
							$.ajax({ 
								url: "./transceiver.php",
								type: "POST",
								data: msg,
								success: function(data){
									//data = $.parseJSON(data);
									console.log (data);
									if (data.success) {
										if (data.posts) {
											for (key in data.posts) {
												if (key != 0) {
													
													post = data.posts[key];
													console.log(data.posts[key], post);
												
													user = post.username;
													timestamp = post.time;//
													msg = decodeURI(decodeURIComponent(post.text));
													
													var name = $('<span class="m-name"></span>').append(user + " ");
													var date = $('<span class="m-date"></span>').append(dateFormat(timestamp * 1000, "H:MM d/mm") + " ");
													var text = $('<span class="m-text"></span>').append( msg + " ");
																										
													if (post.private != "false") {
														if (post.privatename != _user) {
															text = $('<span class="m-text"></span>').append( "to " + post.privatename + ": " + msg + " ");
														}
														$("#chat ul").append( $('<li></li>').append( name, date, text ).css("background", "#DED"));
													} else {
														$("#chat ul").append( $('<li></li>').append( name, date, text ));
													}
												}
											}
										}									
									}
								}, 
								dataType: "json"
							});
							
						}, 1000);
						
					} else {
						// @TODO: ERROR POPUP
					}
				} );
			}
			
			function SendMessage() {
				//console.log($("#message-box").val());
				var msg = $("#message-box").val();
				//console.log(msg);
				
				if (msg != "") {
					var date = (new Date());				
					var timestamp = Math.round(date.getTime() / 1000);
					
					var msg = { entity : "post", action : "post", user : _user, userkey: _userkey, datetime : timestamp, message: encodeURI( msg ) };
					
					if ($("#privatePanel").css("display") == "block") {
						var private_user = $("#private-name").val();
						var private_key = $("#private-key").val();
						
						msg["private"] = private_key;
					} else {
						msg["private"] = "null";
					}
					
					console.log(msg);
					
					$.ajax( {
						url: "./transceiver.php",
						type: "POST",
						data: msg
					} ).done( function (data) {
						$("#message-box").val("");
						$("#privatePanel").hide();
					} );
				}
			}
			
			function RenameUser() {
				var newname = $("#rename-name").val();
				
				if (newname != "") {
					var date = (new Date());				
					var timestamp = Math.round(date.getTime() / 1000);
					
					var msg = { entity : "user", action : "rename", user : newname, userkey: _userkey, datetime : timestamp };
					console.log(msg);
					
					$.ajax( {
						url: "./transceiver.php",
						type: "POST",
						data: msg,
						success: function(data){
							data = $.parseJSON(data);
							console.log (data);
							if (data.success) {
								_user = data.username;									
							}
						}, 
					} ).done( function (data) {
					} );
				}
			}
			
			// Handling messages
			$("#message-button").click( function() { SendMessage(); });
			$("#message-box").keypress(function(e) {
				if(e.which == 13) {
					SendMessage();
				}
			});
			
			$("#rename-button").click( function() { RenameUser(); });
			$("#rename-button").keypress(function(e) {
				if(e.which == 13) {
					RenameUser();
				}
			});
			
			$("#private-close").click (function() {
				$("#privatePanel").hide();
			});
		});
	}
	</script>
</head>
<body>
	<div id="chatPanel">
        <div id="chat"><ul><li>
                    <span class="m-name">Name</span>
					<span class="m-date">13:03 9/12</span>
                    <span class="m-text">tessadsda da das asd ad </span>
                </li>
                <li>
                    <span>Name:</span>
                    <span>tessadsda da das asd ad </span>
                </li>
                <li>
                    <span>Name:</span>
                    <span>tessadsda da das asd ad </span>
                </li>
                <li>
                    <span>Name:</span>
                    <span>tessadsda da das asd ad </span>
                </li>
                <li>
                    <span>Name:</span>
                    <span>tessadsda da das asd ad </span>
                </li></ul></div>
		<div id="contacts"><ul><li>
                    <span>fRIEND:</span>
                </li>
                <li>
                    <span>fRIEND:</span>
                </li>
                <li>
                    <span>fRIEND:</span>
                </li>
                <li>
                    <span>fRIEND:</span>
                </li>
                <li>
                    <span>fRIEND:</span>
                </li>
                <li>
                    <span>fRIEND:</span>
                </li></ul></div>
	</div>
	<div id="messagePanel">
		<textarea id="message-box" placeholder="Введите сообщение"></textarea>
		<input id="message-button" type="submit" />
	</div>
	<div id="privatePanel">
		<a id="private-close" href="#">close</a>
		<span>Private for:</span>
		<span id="private-name">USERNAME</span>
		<input type="hidden" id="private-key" value ="123"/>
	</div>
	<div id="renamePanel">
		<span>Rename to:</span>
		<input type="text" id="rename-name" value="" placeholder="Введите новое имя"/>
		<input id="rename-button" type="submit" />
	</div>
</body>
</html>
